package com.concurrence;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ConditionDemo..  两个线程交替打印奇偶数
 *
 * @author Lizhong
 * @date 2019/4/4
 */
public class ConditionDemo {
    static Lock lock = new ReentrantLock();

    static Condition odd = lock.newCondition();
    static Condition even = lock.newCondition();
    volatile static Integer j = 0;

    public static void main(String[] args) {
        A a = new A(odd);
        B b = new B(even);
        a.start();
        b.start();
    }

    static class A extends Thread {
        public A(Condition condition) {
            this.condition = condition;
        }

        Condition condition;

        @Override
        public void run() {
            for (; ; ) {
                method01();
            }
        }
    }

    static class B extends Thread {
        public B(Condition condition) {
            this.condition = condition;
        }

        Condition condition;

        @Override
        public void run() {
            for (; ; ) {
                method02();
            }
        }
    }

    public static void method01() {
        lock.lock();
        try {
            if (j % 2 == 1) {
                System.out.println(Thread.currentThread().getName() + "=" + j);
                j++;

            } else {
                even.signal();
                odd.await();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }


    public static void method02() {
        lock.lock();
        try {
            if (j % 2 == 0) {
                System.out.println(Thread.currentThread().getName() + "=" + j);
                j++;
            } else {
                odd.signal();
                even.await();
            }
            // Thread.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
